/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.cookor.poi.modules.sys.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cookor.poi.common.service.BaseService;
import com.cookor.poi.common.utils.ResultUtil;
import com.cookor.poi.common.utils.StringUtils;
import com.cookor.poi.common.utils.UserAgentUtils;
import com.cookor.poi.utils.HttpUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 手机端视图拦截器
 * @author ThinkGem
 * @version 2014-9-1
 */
public class ApiInterceptor extends BaseService implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
//		logger.info(HttpUtils.getClientIP(request)+",View: " + HttpUtils.getVisitUrl(request));
		if(StringUtils.isBlank(request.getHeader("vCode"))){
			ResultUtil resultUtil = new ResultUtil(ResultUtil.ERROR_CODE);
			resultUtil.setError("平台已升级，请右上角刷新页面！");
			falseResult(response, resultUtil);
			return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
			Object handler, Exception ex) throws Exception {

	}

	public void falseResult(HttpServletResponse response, Object obj) throws IOException {
		response.setContentType("application/json; charset=utf-8");
		PrintWriter writer = response.getWriter();
		writer.print(JSONObject.toJSONString(obj, SerializerFeature.WriteMapNullValue,
				SerializerFeature.WriteDateUseDateFormat));
		writer.close();
		response.flushBuffer();
	}

}
